package com.business.action.admin.database;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.rose.boot.BootStrap;
import net.sf.rose.boot.bean.DatabaseBean;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.BeanWrapper;

@Controller
@RequestMapping("/admin/database")
public class DatabaseAction {

	/**
	 * 获取配置文件保存的版本文件名
	 */
	@ResponseBody
	@RequestMapping("/getVersion.do")
	public PageBean getVersion(HttpServletRequest request) {
		PageBean page = new PageBean();
		double version = Service.getMeta().getDatabaseFileVersion();
		// version = version + 0.01;
		String fileName = version + "";
		fileName = fileName.replace('.', '-');
		fileName = "database-" + fileName + ".ini";
		page.setData(fileName);
		return page;
	}

	/**
	 * 获取数据库连接定义列表
	 */
	@ResponseBody
	@RequestMapping("/list.do")
	public PageBean list(HttpServletRequest request) {
		PageBean page = new PageBean();
		page.setData(BootStrap.getBootBean().getDatabaseList());
		return page;
	}

	/**
	 * 获取数据库连接定义列表
	 */
	@ResponseBody
	@RequestMapping("/save.do")
	public PageBean save(HttpServletRequest request, DatabaseBean bean) {
		PageBean page = new PageBean();
		Map<?, ?> m = request.getParameterMap();
		List<DatabaseBean> list = BootStrap.getBootBean().getDatabaseList();
		for(DatabaseBean db :list){
			if(db.getDatabaseName().equals(bean.getDatabaseName())){
				BeanWrapper bw = new BeanWrapper();
				bw.setWrappedInstance(db);
				for (Object key : m.keySet()) {
					String[] arr = (String[]) m.get(key);
					bw.set(key.toString(), arr[0]);
				}
				return page;
			}
		}
		list.add(bean);
		return page;
	}

}
